# -*- coding:utf-8 -*-
# !/usr/bin/env python
"""
Date: 2021/12/6 21:59
Desc: 上海黄金交易所-数据资讯-行情走势
https://www.sge.com.cn/sjzx/mrhq
"""
import pandas as pd
import requests
from bs4 import BeautifulSoup


def spot_symbol_list_sge() -> list:
    """
    上海黄金交易所-数据资讯-行情走势-品种列表
    https://www.sge.com.cn/sjzx/mrhq
    :return: 品种列表
    :rtype: pandas.DataFrame
    """
    url = "https://www.sge.com.cn/sjzx/mrhq"
    r = requests.get(url)
    soup = BeautifulSoup(r.text, "lxml")
    value_item = soup.find(attrs={"id": "instidsle"}).find_all("option")
    symbol_list = [item.text for item in value_item]
    return symbol_list


def spot_hist_sge(symbol: str = "Au99.99") -> pd.DataFrame:
    """
    上海黄金交易所-数据资讯-行情走势-历史数据
    https://www.sge.com.cn/sjzx/mrhq
    :param symbol: choice of {'Au99.99', 'Au99.95', 'Au100g', 'Pt99.95', 'Ag(T+D)', 'Au(T+D)', 'mAu(T+D)', 'Au(T+N1)', 'Au(T+N2)', 'Ag99.99', 'iAu99.99', 'Au99.5', 'iAu100g', 'iAu99.5', 'PGC30g', 'NYAuTN06', 'NYAuTN12'}; 可以通过 ak.spot_symbol_list_sge() 获取该品种列表
    :type symbol: str
    :return: 历史数据
    :rtype: pandas.DataFrame
    """
    url = "https://www.sge.com.cn/graph/Dailyhq"
    payload = {"instid": symbol}
    r = requests.post(url, data=payload)
    data_json = r.json()
    temp_df = pd.DataFrame(data_json["time"])
    temp_df.columns = [
        "date",
        "open",
        "close",
        "high",
        "low",
    ]
    return temp_df


if __name__ == "__main__":
    spot_list = spot_symbol_list_sge()
    print(spot_list)

    spot_hist_sge_df = spot_hist_sge(symbol='Au99.99')
    print(spot_hist_sge_df)

    for spot in spot_list:
        spot_hist_sge_df = spot_hist_sge(symbol=spot)
        print(spot_hist_sge_df)
